package org.kl.wx.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.utils.CRUDUtils;
import org.kl.bf.utils.KLDynamicSpecifications;
import org.kl.bf.utils.KLSearchFilter;
import org.kl.wx.entity.MessageSend;
import org.kl.wx.repository.MessageSendDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
public class MessageSendService {
	private MessageSendDao messageSendDao;

	public MessageSend getMessageSend(String id) {
		return messageSendDao.find(MessageSend.class, id);
	}

	public void saveMessageSend(MessageSend entity) {
		messageSendDao.save(entity);
	}

	public void deleteMessageSend(String id) {
		messageSendDao.delete(id);
	}

	public String multiDelete(String ids) {
		String[] idArray = StringUtils.split(ids, ",");
		int i = 0;
		for (String id : idArray) {
			if (StringUtils.isNotBlank(id)) {
				messageSendDao.delete(id);
				i++;
			}
		}
		return "删除" + i + "条记录";
	}

	public List<MessageSend> getAllMessageSend() {
		return messageSendDao.findAll();
	}

	/**
	 * 按条件查询
	 */
	public List<MessageSend> getMessageSend(Map<String, Object> searchParams) {
		Specification<MessageSend> spec = buildSpecification(searchParams);
		return messageSendDao.findAll(spec);
	}

	/**
	 * 按条件分页查询
	 */
	public Page<MessageSend> getMessageSend(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType, String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<MessageSend> spec = buildSpecification(searchParams);

		return messageSendDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<MessageSend> buildSpecification(Map<String, Object> searchParams) {
		Map<String, KLSearchFilter> filters = KLSearchFilter.parse(searchParams);
		Specification<MessageSend> spec = KLDynamicSpecifications.byKLSearchFilter(filters.values(), MessageSend.class);
		return spec;
	}

	@Autowired
	public void setMessageSendDao(MessageSendDao messageSendDao) {
		this.messageSendDao = messageSendDao;
	}

}
